package com.lzjn.code.web.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;


public class FileUtil {
	
	public static String getFileName(String filePath){
		
		if(StringUtils.isNotEmpty(filePath)){
			
			String fileName = filePath;
			
			if(filePath.contains("/")){
				
				fileName = filePath.substring(filePath.lastIndexOf("/")+1);
			}
			
			return fileName;
		}

		return null;
	}
	
	public static void downloadFile(String filePath,HttpServletResponse response) throws Exception{
		
		String fileName = getFileName(filePath);
		Long fileLength = new File(filePath).length();
		
		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("UTF-8"), "ISO8859-1"));
			response.setContentLength(fileLength.intValue());
			
			in = new BufferedInputStream(new FileInputStream(filePath));
			
			out = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = in.read(buff, 0, buff.length))) {
				out.write(buff, 0, bytesRead);
			}
			
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}